package com.hzncc.flowable_diboot.service.invoicemanage.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Texts;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.diboot.core.binding.Binder;
import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.holder.ThreadLocalHolder;
import com.diboot.core.util.JSON;
import com.diboot.core.util.S;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.file.util.HttpHelper;
import com.hzncc.flowable_diboot.contract.entity.ContractAudit;
import com.hzncc.flowable_diboot.contract.entity.ContractProduct;
import com.hzncc.flowable_diboot.contract.entity.SalesContract;
import com.hzncc.flowable_diboot.contract.service.ContractAuditService;
import com.hzncc.flowable_diboot.contract.service.SalesContractService;
import com.hzncc.flowable_diboot.contract.vo.*;
import com.hzncc.flowable_diboot.delivery.entity.DeliveryDetail;
import com.hzncc.flowable_diboot.delivery.entity.DeliveryProduct;
import com.hzncc.flowable_diboot.delivery.entity.DeliveryRegister;
import com.hzncc.flowable_diboot.delivery.service.DeliveryRegisterService;
import com.hzncc.flowable_diboot.delivery.vo.DeliveryFormVO;
import com.hzncc.flowable_diboot.dto.invoicemanage.InvoiceFormDTO;
import com.hzncc.flowable_diboot.dto.invoicemanage.InvoiceRegisterDTO;
import com.hzncc.flowable_diboot.entity.SapCustomer;
import com.hzncc.flowable_diboot.entity.invoicemanage.InvoiceProduct;
import com.hzncc.flowable_diboot.enums.ContractAuditStatusEnum;
import com.hzncc.flowable_diboot.enums.ItemtypeEnum;
import com.hzncc.flowable_diboot.enums.RegisterTypeEnum;
import com.hzncc.flowable_diboot.exception.BusinessException;
import com.hzncc.flowable_diboot.project_contracts.entity.ProjectContractAudit;
import com.hzncc.flowable_diboot.project_contracts.entity.ProjectSamContract;
import com.hzncc.flowable_diboot.project_contracts.service.ProjectContractAuditService;
import com.hzncc.flowable_diboot.project_contracts.vo.ProjectContractAuditDetailVO;
import com.hzncc.flowable_diboot.project_contracts.vo.ProjectContractItemDetailVO;
import com.hzncc.flowable_diboot.service.invoicemanage.InvoiceProductService;
import com.hzncc.flowable_diboot.util.NumberToRMBUtils;
import com.hzncc.flowable_diboot.util.WordUtils;
import com.hzncc.flowable_diboot.vo.invoicemanage.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.diboot.core.service.impl.BaseServiceImpl;

import com.hzncc.flowable_diboot.entity.invoicemanage.InvoiceRegister;

import com.hzncc.flowable_diboot.mapper.invoicemanage.InvoiceRegisterMapper;
import com.hzncc.flowable_diboot.service.invoicemanage.InvoiceRegisterService;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;


/**
* 开票登记 相关Service实现类
* @author MyName
* @version 1.0
* @date 2024-11-06
* Copyright © MyCorp
*/
@Slf4j
@Service
public class InvoiceRegisterServiceImpl extends BaseServiceImpl<InvoiceRegisterMapper, InvoiceRegister> implements InvoiceRegisterService {
    
    @Resource
    private InvoiceRegisterMapper invoiceRegisterMapper;

    @Resource
    private InvoiceProductService invoiceProductService;
    
    @Resource
    private DeliveryRegisterService deliveryRegisterService;

    @Resource
    private SalesContractService salesContractService;

    @Resource
    private ContractAuditService contractAuditService;

    @Resource
    private ProjectContractAuditService projectContractAuditService;

    @Override
    public List<InvoiceFormVO> getInvoiceForms(InvoiceFormDTO invoiceFormDTO) {
        List<InvoiceRegister> invoiceRegisters = invoiceRegisterMapper.getInvoiceForms(invoiceFormDTO);
        return Binder.convertAndBindRelations(invoiceRegisters, InvoiceFormVO.class);
    }

    @Override
    public List<InvoiceFormVO> getInvoiceForms(InvoiceFormDTO invoiceFormDTO, Pagination pagination) {
        Page<Object> page = pagination.toPage(InvoiceRegister.class);
        List<InvoiceRegister> invoiceRegisterList = invoiceRegisterMapper.getInvoiceForms(invoiceFormDTO, page);
        List<InvoiceFormVO> invoiceFormVOS = Binder.convertAndBindRelations(invoiceRegisterList, InvoiceFormVO.class);
        pagination.setTotalCount(page.getTotal());
        return invoiceFormVOS;
    }

    @Override
    public Map<String, String> getInvoiceCodeList(String registerType) {
        Map<String,String> result = new HashMap<>();
        LambdaQueryWrapper<InvoiceRegister> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(registerType),InvoiceRegister::getRegisterType,registerType).eq(InvoiceRegister::isDeleted,0);
        List<InvoiceRegister> entityList = this.getEntityList(queryWrapper);
        if (!CollectionUtils.isEmpty(entityList)){
            result = entityList.stream().collect(Collectors.toMap(InvoiceRegister::getId,InvoiceRegister::getDeliveryCode));
        }
        return result;
    }

    @Override
    public String printReceipt(HttpServletResponse response, List<String> invoiceRegisterIds) throws Exception {
        // 查询合同
        List<InvoiceRegister> invoiceRegisterList = this.getEntityListByIds(invoiceRegisterIds);
        List<InvoiceRegisterDetailVO> invoiceRegisterDetailVOS = Binder.convertAndBindRelations(invoiceRegisterList, InvoiceRegisterDetailVO.class);
        String resourceFilePath = WordUtils.getResourceFilePath("word/invoice-receipt.docx");
        String tempDir = WordUtils.getTemplateFilePath() + System.currentTimeMillis() + "/";
        File td = new File(tempDir);
        if (!td.exists()) {
            td.mkdir();
        }
        // 构建参数
        Map<String, Object> params = new HashMap<>();
        BigDecimal invoiceAmountTotal = invoiceRegisterDetailVOS.stream().map(InvoiceRegisterDetailVO::getInvoiceAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
        params.put("invoiceAmountTotal",invoiceAmountTotal);
        String invoiceAmountTotalCh = NumberToRMBUtils.convert(invoiceAmountTotal);
        params.put("invoiceAmountTotalCh",invoiceAmountTotalCh);
        List<Map> items = new ArrayList<>();
        for (InvoiceRegisterDetailVO invoiceRegisterDetailVO : invoiceRegisterDetailVOS) {
            Map item = new HashMap();
            item.put("contractCode",invoiceRegisterDetailVO.getInvoiceProduct().getContractCode());
            item.put("customerName",invoiceRegisterDetailVO.getInvoiceProduct().getRecipientLabel());
            item.put("orderItem",invoiceRegisterDetailVO.getInvoiceProduct().getOrderItem());
            item.put("orderModel",invoiceRegisterDetailVO.getInvoiceProduct().getOrderModel());
            item.put("invoiceAmount",invoiceRegisterDetailVO.getInvoiceAmount());
            item.put("invoiceNo",invoiceRegisterDetailVO.getInvoiceNo());
            item.put("invoiceCount",invoiceRegisterDetailVO.getInvoiceCount());
            items.add(item);
        }
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure conf = Configure.builder().bind("items", policy).build();
        params.put("items", items);
        String fileName = "回执单" + System.currentTimeMillis() + ".docx";
        String filePath = tempDir + fileName;
        try (XWPFTemplate template = XWPFTemplate.compile(resourceFilePath, conf).render(params); FileOutputStream fos = new FileOutputStream(filePath)) {
            template.write(fos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        File file = new File(filePath);
        if (!file.exists()) {
            throw new BusinessException("文件不存在");
        }
        HttpHelper.downloadLocalFile(file, fileName, response);
        return filePath;
    }

    @Override
    public Boolean syncInvoiceRegister(SyncInvoiceRegisterVO syncInvoiceRegisterVO) {
        if (ObjectUtils.isEmpty(syncInvoiceRegisterVO)){
            throw new BusinessException("同步数据为空");
        }
        if (StringUtils.isEmpty(syncInvoiceRegisterVO.getSalesOrganization())){
            throw new BusinessException("sap销售组织为空");
        }
        if (StringUtils.isEmpty(syncInvoiceRegisterVO.getInvoiceCategory())){
            throw new BusinessException("sap开票类型为空");
        }
        if (StringUtils.isEmpty(syncInvoiceRegisterVO.getSapCertCode())){
            throw new BusinessException("sap发票凭证号为空");
        }
        if (StringUtils.isEmpty(syncInvoiceRegisterVO.getSapInvoiceItem())){
            throw new BusinessException("sap发票行项目为空");
        }
        String registerType = RegisterTypeEnum.normal.getCode();//默认常规发货登记
        String salesOrganization = syncInvoiceRegisterVO.getSalesOrganization();
        String invoiceCategory = syncInvoiceRegisterVO.getInvoiceCategory();
        String sapContractCode = syncInvoiceRegisterVO.getSapCode();
        String sapOrderCode = syncInvoiceRegisterVO.getSapOrderCode();
        String sapDeliveryCode = syncInvoiceRegisterVO.getSapDeliveryCode();
        String sapCertCode = syncInvoiceRegisterVO.getSapCertCode();
        String invoiceItem = syncInvoiceRegisterVO.getSapInvoiceItem();
        LocalDateTime invoiceCertTime = syncInvoiceRegisterVO.getInvoiceCertTime();
        BigDecimal invoiceAmount = syncInvoiceRegisterVO.getInvoiceAmount();
        String payer = syncInvoiceRegisterVO.getPayer();
        String delFlag = syncInvoiceRegisterVO.getDelFlag();
        //发货信息
        LambdaUpdateWrapper<DeliveryRegister> deliveryUpdate = new LambdaUpdateWrapper<>();
        deliveryUpdate.set(DeliveryRegister::getInvoiced,"1").set(DeliveryRegister::getInvoiceTime,invoiceCertTime).eq(DeliveryRegister::getDeliveryCode,sapDeliveryCode);
        ThreadLocalHolder.setIgnoreInterceptor();
        deliveryRegisterService.updateEntity(deliveryUpdate);
        // 销售合同信息
        LambdaQueryWrapper<SalesContract> salesContractQuery = new LambdaQueryWrapper<>();
        salesContractQuery.eq(SalesContract::getSapCode,sapContractCode);
        // 设置忽略拦截器
        ThreadLocalHolder.setIgnoreInterceptor();
        SalesContractListVO salesContract = salesContractService.getViewObject(salesContractQuery, SalesContractListVO.class);
        if (ObjectUtils.isEmpty(salesContract)){
            throw new BusinessException("销售合同不存在");
        }
        SalesContractExtListVO salesContractExt = salesContract.getExt();
        //客户信息
        SapCustomer sapCustomer = salesContract.getSapCustomer();
        //合同项目
        ContractProduct contractProduct = salesContract.getProduct();
        ProjectSamContract projectSamContract = salesContract.getProjectSamContract();
        BigDecimal productPrice = new BigDecimal(0);
        if (StringUtils.isNotEmpty(salesContract.getProjectContractId())&&ObjectUtils.isNotEmpty(projectSamContract)){
            productPrice = projectSamContract.getTotal();
        }else if (ObjectUtils.isNotEmpty(contractProduct)){
            productPrice = contractProduct.getProductPrice();
        }
        if ("1".equals(delFlag)){
            //冲销登记
            registerType = RegisterTypeEnum.reversal.getCode();
            LambdaUpdateWrapper<InvoiceRegister> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(InvoiceRegister::getRegisterType,registerType)
                    .eq(InvoiceRegister::getSalesOrganization,salesOrganization)
                    .eq(InvoiceRegister::getInvoiceCategory,invoiceCategory)
                    .eq(InvoiceRegister::getSapCertCode,sapCertCode)
                    .eq(InvoiceRegister::getInvoiceItem,invoiceItem);
            ThreadLocalHolder.setIgnoreInterceptor();
            this.update(updateWrapper);
        }else if ("0".equals(delFlag)){
            //登记信息
            LambdaQueryWrapper<InvoiceRegister> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(InvoiceRegister::getSalesOrganization,salesOrganization)
                    .eq(InvoiceRegister::getInvoiceCategory,invoiceCategory)
                    .eq(InvoiceRegister::getSapCertCode,sapCertCode)
                    .eq(InvoiceRegister::getInvoiceItem,invoiceItem);
            ThreadLocalHolder.setIgnoreInterceptor();
            InvoiceRegister viewObject = this.getSingleEntity(queryWrapper);
            if (ObjectUtils.isNotEmpty(viewObject)){
                ThreadLocalHolder.setIgnoreInterceptor();
                invoiceProductService.deleteEntity("invoice_register_id",viewObject.getId());
                ThreadLocalHolder.setIgnoreInterceptor();
                this.deleteEntity(viewObject.getId());
            }
            InvoiceRegister invoiceRegister = new InvoiceRegister();
            invoiceRegister.setTenantId(salesContract.getTenantId()).setRegistered("0").setRegisterType(registerType)
                    .setSalesOrganization(salesOrganization).setInvoiceCategory(invoiceCategory)
                    .setSapContractCode(sapContractCode).setSapOrderCode(sapOrderCode).setDeliveryCode(sapDeliveryCode)
                    .setSapCertCode(sapCertCode).setInvoiceItem(invoiceItem).setSapInvoiceCertTime(invoiceCertTime).setInvoiceAmount(invoiceAmount).setPayer(payer);
            // 设置忽略拦截器
            ThreadLocalHolder.setIgnoreInterceptor();
            this.createEntity(invoiceRegister);

            String singer = "";
            String finalUser = "";
            if (StringUtils.isNotEmpty(salesContract.getProjectContractId())){
                LambdaQueryWrapper<ProjectContractAudit> projectContractAuditQuery = new LambdaQueryWrapper<>();
                projectContractAuditQuery.eq(ProjectContractAudit::getContractCode, salesContract.getOrderCode()).ne(ProjectContractAudit::getContractStatus,0).eq(ProjectContractAudit::isDeleted,0);
                ThreadLocalHolder.setIgnoreInterceptor();
                List<ProjectContractAudit> projectContractList = projectContractAuditService.getEntityList(projectContractAuditQuery);
                ProjectContractAudit projectContractDetailByCode = projectContractList.stream().max(Comparator.comparing(ProjectContractAudit::getContractVersion)).get();
                singer = projectContractDetailByCode.getSigner();
            }else {
                LambdaQueryWrapper<ContractAudit> contractAuditQuery = new LambdaQueryWrapper<>();
                contractAuditQuery.eq(ContractAudit::getContractCode, salesContract.getOrderCode()).ne(ContractAudit::getContractStatus,0).eq(ContractAudit::isDeleted, 0);
                ThreadLocalHolder.setIgnoreInterceptor();
                List<ContractAudit> contractList = contractAuditService.getEntityList(contractAuditQuery);
                ContractAudit contractDetailByCode = contractList.stream().max(Comparator.comparing(ContractAudit::getContractVersion)).get();
                singer = contractDetailByCode.getSigner();
                finalUser = contractDetailByCode.getFinalUser();
            }
            InvoiceProduct invoiceProduct = new InvoiceProduct();
            invoiceProduct.setTenantId(salesContract.getTenantId())
                    .setInvoiceRegisterId(invoiceRegister.getId())
                    .setSapContractCode(sapContractCode)
                    .setContractCode(salesContract.getOrderCode())
                    .setContractType(salesContractExt == null ? null : salesContractExt.getCompanyContractType())
                    .setRecipient(salesContract.getRecipient())
                    .setSalesTerritory(ObjectUtils.isNotEmpty(salesContract.getSalesTerritory())?salesContract.getSalesTerritory():"")
                    .setBusinessDept(salesContract.getBusinessDept())
                    .setSigner(singer)
                    .setProvince(ObjectUtils.isNotEmpty(sapCustomer)?sapCustomer.getProvince():"")
                    .setPayType(salesContract.getPaymentMethod())
                    .setCity("")
                    .setOrderItem(salesContract.getOrderItem())
                    .setOrderModel(salesContract.getOrderModel())
                    .setMachineToolType(ObjectUtils.isNotEmpty(salesContractExt)&&ObjectUtils.isNotEmpty(salesContractExt.getMachineToolType())?salesContractExt.getMachineToolType():"")
                    .setSupportingMachineTool(ObjectUtils.isNotEmpty(salesContractExt)&&ObjectUtils.isNotEmpty(salesContractExt.getSupportingMachineTool())?salesContractExt.getSupportingMachineTool():"")
                    .setProductSeries("")
                    .setGrade(ObjectUtils.isNotEmpty(salesContractExt)&&ObjectUtils.isNotEmpty(salesContractExt.getGrade())?salesContractExt.getGrade():"")
                    .setProductPrice(productPrice)
                    .setAccountAssignment(ObjectUtils.isNotEmpty(sapCustomer)?sapCustomer.getDis():"")
                    .setFinalUser(finalUser);
            // 设置忽略拦截器
            ThreadLocalHolder.setIgnoreInterceptor();
            invoiceProductService.createEntity(invoiceProduct);
            LambdaQueryWrapper<InvoiceRegister> invoiceRegisterQuery = new LambdaQueryWrapper<>();
            invoiceRegisterQuery.eq(InvoiceRegister::getSapContractCode,sapContractCode).eq(InvoiceRegister::isDeleted,0);
            ThreadLocalHolder.setIgnoreInterceptor();
            List<InvoiceRegister> invoiceRegisterList = this.getEntityList(invoiceRegisterQuery);
            BigDecimal invoiceAmountTotal = invoiceRegisterList.stream().map(InvoiceRegister::getInvoiceAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            LambdaUpdateWrapper<SalesContract> salesContractUpdate = new LambdaUpdateWrapper<>();
            if (invoiceAmountTotal.compareTo(new BigDecimal(salesContract.getFixedDiscountAmount()))<0){
                salesContractUpdate.set(SalesContract::getInvoiceStatus,"1").eq(SalesContract::getId,salesContract.getId());
            }else if (invoiceAmountTotal.compareTo(new BigDecimal(salesContract.getFixedDiscountAmount()))>=0){
                salesContractUpdate.set(SalesContract::getInvoiceStatus,"0").eq(SalesContract::getId,salesContract.getId());
            }
            ThreadLocalHolder.setIgnoreInterceptor();
            salesContractService.updateEntity(salesContractUpdate);
        }
        return true;
    }

    @Override
    public List<InvoiceRegisterListVO> getPage(InvoiceRegisterDTO invoiceRegisterDTO, Pagination pagination) {
        if ("1".equals(invoiceRegisterDTO.getMustSapContractCode()) && StringUtils.isEmpty(invoiceRegisterDTO.getSapContractCode())){
            return new ArrayList<>();
        }
        String contractCode = invoiceRegisterDTO.getContractCode();
        invoiceRegisterDTO.setContractCode(null);
        QueryWrapper queryWrapper = QueryBuilder.toQueryWrapper(invoiceRegisterDTO);
        pagination.setOrderBy("sapInvoiceCertTime:DESC,sapContractCode:DESC,sapOrderCode:DESC");
        if (pagination != null && V.isEmpty(pagination.getOrderBy())) {
            pagination.setOrderBy(Pagination.ORDER_BY_ID_DESC);
        }
        if (contractCode != null) {
            List<InvoiceProduct> list = invoiceProductService.lambdaQuery().select(InvoiceProduct::getInvoiceRegisterId).eq(InvoiceProduct::getContractCode, contractCode).list();
            if (list != null && list.size() > 0) {
                queryWrapper.in("id", list.stream().map(InvoiceProduct::getInvoiceRegisterId).collect(Collectors.toList()));
            }
        }
        return this.getViewObjectList(queryWrapper,pagination,InvoiceRegisterListVO.class);
    }

    @Override
    public InvoiceRegisterDetailVO getDetail(String id) {
        InvoiceRegisterDetailVO viewObject = this.getViewObject(id, InvoiceRegisterDetailVO.class);
        if (ObjectUtils.isEmpty(viewObject)){
            throw new BusinessException("发货登记信息不存在");
        }
        return viewObject;
    }

    @Override
    public Boolean saveInvoiceRegister(InvoiceRegisterDetailVO invoiceRegisterDetailVO) {
        boolean success = this.createEntity(invoiceRegisterDetailVO);
        InvoiceProductListVO invoiceProduct = invoiceRegisterDetailVO.getInvoiceProduct();
        if (ObjectUtils.isNotEmpty(invoiceProduct)){
            invoiceProduct.setInvoiceRegisterId(invoiceRegisterDetailVO.getId());
            invoiceProductService.createEntity(invoiceProduct);
        }
        return success;
    }

    @Override
    public Boolean updateInvoiceRegister(InvoiceRegisterDetailVO invoiceRegisterDetailVO) {
        boolean success = this.updateById(invoiceRegisterDetailVO);
        InvoiceProductListVO invoiceProduct = invoiceRegisterDetailVO.getInvoiceProduct();
        if (ObjectUtils.isNotEmpty(invoiceProduct)){
            invoiceProduct.setInvoiceRegisterId(invoiceRegisterDetailVO.getId());
            invoiceProductService.updateEntity(invoiceProduct);
        }
        return success;
    }

    @Override
    @Transactional
    public Boolean updateInvoiceRegisterBatch(List<InvoiceRegisterDetailVO> invoiceRegisterDetailVOS) {
        List<InvoiceProduct> invoiceProductList = new ArrayList<>();
        for (InvoiceRegisterDetailVO invoiceRegisterDetailVO : invoiceRegisterDetailVOS){
            LambdaQueryWrapper<InvoiceProduct> invoiceProductQuery = new LambdaQueryWrapper<>();
            invoiceProductQuery.eq(InvoiceProduct::getInvoiceRegisterId,invoiceRegisterDetailVO.getId());
            InvoiceProduct invoiceProduct = invoiceProductService.getSingleEntity(invoiceProductQuery);
            invoiceRegisterDetailVO.getInvoiceProduct().setId(invoiceProduct.getId());
            invoiceProductList.add(invoiceRegisterDetailVO.getInvoiceProduct());
        }
        invoiceProductService.updateEntities(invoiceProductList);
        return this.updateEntities(invoiceRegisterDetailVOS);
    }

    @Override
    public Boolean deleteDeliveryRegister(String id) {
        //查询发货关联合同项目信息
        LambdaQueryWrapper<InvoiceProduct> productQw = new LambdaQueryWrapper<>();
        productQw.eq(InvoiceProduct::getInvoiceRegisterId,id);
        invoiceProductService.deleteEntities(productQw);
        return this.deleteEntity(id);
    }

    @Override
    public Boolean deleteDeliveryRegisterBatch(List<String> ids) {
        //查询发货关联合同项目信息
        LambdaQueryWrapper<InvoiceProduct> productQw = new LambdaQueryWrapper<>();
        productQw.in(InvoiceProduct::getInvoiceRegisterId,ids);
        invoiceProductService.deleteEntities(productQw);
        return this.deleteEntities(ids);
    }

    private String genInvoiceNo(){
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replace("-","");
        int randomValue = Integer.parseInt(uuidStr.substring(0,8),16);
        return "ab" + randomValue;
    }
}